package com.hdoit.ares.web.active.apis;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hdoit.ares.logical.acc.model.AccountInfo;
import com.hdoit.ares.logical.acc.model.GoldenBeanDetail;
import com.hdoit.ares.logical.acc.service.IAccountInfoService;
import com.hdoit.ares.logical.acc.service.IGoldenBeanDetailService;
import com.hdoit.ares.logical.acti.service.IActiTaskService;
import com.hdoit.ares.logical.active.model.Sign;
import com.hdoit.ares.logical.active.service.ISignService;
import com.hdoit.ares.logical.cust.model.Customer;
import com.hdoit.ares.logical.cust.service.ICustomerService;
import com.hdoit.ares.selfcommon.enums.acc.GoldenBeanType;
import com.hdoit.ares.selfcommon.enums.acc.HesitatePeriodState;
import com.hdoit.ares.selfcommon.enums.acc.State;
import com.tennetcn.common.enums.ModelStatus;
import com.tennetcn.common.enums.pub.YesOrNo;
import com.tennetcn.common.message.ApiLoginModel;
import com.tennetcn.common.utils.CommonUtils;
import com.tennetcn.common.utils.DateUtils;
import com.tennetcn.common.utils.RandomUtils;
import com.tennetcn.component.webapi.BaseApi;
import com.tennetcn.component.webapi.ResponseModel;
import com.tennetcn.component.webapi.ResponseStatus;

@Controller
@RequestMapping(value = "/api/v1/signAres/",method = {RequestMethod.GET,RequestMethod.POST},produces="application/json;charset=utf-8")
@Api(value="/api/v1/signAres/")
@CrossOrigin(origins = "*",maxAge = 3600)
public class SignAresApi extends BaseApi{
	
	private ISignService signService;
	private ICustomerService customerService;
	private IAccountInfoService accountInfoService;
	private IGoldenBeanDetailService goldenBeanDetailService;
	private IActiTaskService actiTaskService;
		
	public IActiTaskService getActiTaskService() {
		return actiTaskService;
	}
	@Resource
	public void setActiTaskService(IActiTaskService actiTaskService) {
		this.actiTaskService = actiTaskService;
	}
	
	public ISignService getSignService() {
		return signService;
	}
	@Resource
	public void setSignService(ISignService signService) {
		this.signService = signService;
	}
	
	public ICustomerService getCustomerService() {
		return customerService;
	}
	@Resource
	public void setCustomerService(ICustomerService customerService) {
		this.customerService = customerService;
	}

	public IAccountInfoService getAccountInfoService() {
		return accountInfoService;
	}
	@Resource
	public void setAccountInfoService(IAccountInfoService accountInfoService) {
		this.accountInfoService = accountInfoService;
	}

	public IGoldenBeanDetailService getGoldenBeanDetailService() {
		return goldenBeanDetailService;
	}
	@Resource
	public void setGoldenBeanDetailService(
			IGoldenBeanDetailService goldenBeanDetailService) {
		this.goldenBeanDetailService = goldenBeanDetailService;
	}

	private final String signApi="sign";
	private final String doSignApi ="doSign";
	
	@ResponseBody
	@RequestMapping(value = signApi)
	@ApiOperation(notes= signApi,httpMethod = "POST" ,value = "进入签到页面")
	public String sign(){
		
		ApiLoginModel apiLoginModel = getApiLoginModel();
		Customer customer = customerService.queryModel(apiLoginModel.getLoginId());
		String custId = customer.getId();
		@SuppressWarnings("deprecation")
		String month = (DateUtils.getCurrent().getMonth()+1)+"";
		@SuppressWarnings("deprecation")
		String day = (DateUtils.getCurrent().getDate())+"";
		
		HashMap<String, Object> val = querySignData(custId, month, day);
		
		
		ResponseModel rm = new ResponseModel();
		
		rm.put("signedDate",val.get("signedDate"));
		rm.put("isSigned",val.get("isSigned"));
		rm.put("alldays",val.get("alldays"));
		rm.put("continuityDays",val.get("continuityDays"));

		return rm.toJson();
	}
	
	@ResponseBody
	@RequestMapping(value = doSignApi)
	@ApiOperation(notes= doSignApi,httpMethod = "POST" ,value = "点击签到请求页面")
	public String doSign(){
		ResponseModel rm = new ResponseModel();

		ApiLoginModel apiLoginModel = getApiLoginModel();
		Customer customer = customerService.queryModel(apiLoginModel.getLoginId());
		String custId = customer.getId();
		@SuppressWarnings("deprecation")
		String month = (DateUtils.getCurrent().getMonth()+1)+"";
		@SuppressWarnings("deprecation")
		String day = (DateUtils.getCurrent().getDate())+"";
		
		HashMap<String, Object> res = new HashMap<String, Object>();

		//再次确认是否重复签到
		HashMap<String, Object> test = querySignData(custId, month, day);		
		if("true".equals(test.get("isSigned")+"")){
			
			res.put("isSigned",true); 
			rm.put("isSigned",true);
			rm.setStatus(ResponseStatus.success);
			rm.setMessage("今日已签到,无需重复签到");
			
			return rm.toJson();
		}
		
		//数据库添加数据
		Sign sign = new Sign();
		sign.setId(CommonUtils.getKeyId());
		sign.setDeleteMark(YesOrNo.no); 
		sign.setCustId(customer.getId());
		sign.setSignDate(DateUtils.getCurrent());
		sign.setSignDays(signService.queryContinuityDays(month,day,custId)+1);
		
		sign.setModelStatus(ModelStatus.add);
		
		res.put("signed", "yes");	
		
		//金豆	
		int goldenBean = 0;
		if(sign.getSignDays()==7){
			goldenBean = 15;
		}else if (sign.getSignDays()==30) {
			goldenBean = 105;
		}else {
			goldenBean = 5;
		}
				
		/*ActiTask actiTask = actiTaskService.queryModelByTaskId(TaskId.sign);
		int goldenBean = Integer.valueOf(actiTask.getReward());
		if(StringUtils.isEmpty(actiTask.getReward())){
			goldenBean=20;
		}*/
		
		res.put("addBean", goldenBean);
		
		//改变总金豆
		AccountInfo accountInfo = accountInfoService.queryModelByCustomerId(customer.getId());			
		accountInfo.setGoldenBean(accountInfo.getGoldenBean()+goldenBean);
		accountInfo.setModelStatus(ModelStatus.update);
		
		//金豆明细
		GoldenBeanDetail goldenBeanDetail = new GoldenBeanDetail();
		goldenBeanDetail.setId(CommonUtils.getKeyId());
		goldenBeanDetail.setAccountNo(accountInfo.getAccountNo());
		goldenBeanDetail.setGoldenBeanType(GoldenBeanType.sign);
		goldenBeanDetail.setTime(DateUtils.getCurrent());
		goldenBeanDetail.setState(State.income);
		goldenBeanDetail.setGoldenBeanAccount(goldenBean);
		goldenBeanDetail.setGoldenBeanBalance(accountInfo.getGoldenBean());
		goldenBeanDetail.setCustomerId(customer.getId());
		goldenBeanDetail.setOutTradeNo("" + System.currentTimeMillis()+RandomUtils.randomInt(1000, 9999));
		goldenBeanDetail.setComment("签到所得");
		goldenBeanDetail.setHesitatePeriodState(HesitatePeriodState.Hesitated);
		goldenBeanDetail.setModelStatus(ModelStatus.add);
		
		if(signService.applyChange(sign)&&accountInfoService.applyChange(accountInfo)&&		goldenBeanDetailService.applyChange(goldenBeanDetail)){
			rm.setStatus(ResponseStatus.success);
		}else{
			rm.setStatus(ResponseStatus.dataError);
			rm.setMessage("处理数据失败");
		}
		
		HashMap<String, Object> val = querySignData(custId, month, day);
		
		res.put("signDay", val.get("signedDate"));
		res.put("isSigned", val.get("isSigned"));
		res.put("alldays", val.get("alldays"));
		res.put("continuityDays", val.get("continuityDays"));

		List<String> params = new ArrayList<String>();

		Iterator<Map.Entry<String, Object>> iter = res.entrySet().iterator();
		iter = res.entrySet().iterator();
		while (iter.hasNext()) {
		@SuppressWarnings("rawtypes")
		Map.Entry entry = (Map.Entry) iter.next();
		String key =(String) entry.getKey();
		params.add(key);
		}		
		
		rm.putObj("res", res, params);

		return rm.toJson();
	}
	
public HashMap<String, Object> querySignData(String custId,String month,String day){
		
		HashMap<String, Object> val = new  HashMap<String, Object>();
		//已签到日期
		List<String> signedDates = signService.querySignedDate(month,custId);	
		List<HashMap<String, String>> signedDate =new ArrayList<HashMap<String,String>>();
		for (String stringDate : signedDates) {
			HashMap<String, String> hashMap= new HashMap<String, String>();
			hashMap.put("signDay", stringDate);
			signedDate.add(hashMap);
		}
		//判断当天签到情况
		Boolean isSigned = signService.queryIsSignedToday(month,day,custId);
		//累计签到天数
		Integer alldays = signService.queryAllSignedDays(month,custId);		
		//连续签到天数
		Integer continuityDays =signService.queryContinuityDays(month,day,custId);		
		
		val.put("signedDate", signedDate);
		val.put("isSigned", isSigned);
		val.put("alldays", alldays);
		val.put("continuityDays", continuityDays);
		
		return val;
	}

}
